/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.service.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 收款明细Controller
 * @author 李超辉
 * @version 2018-04-16
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/recivedDetil")
public class RecivedDetilController extends BaseController {

	@Autowired
	private RecivedDetilService recivedDetilService;
	@Autowired
	private ReceivableService receivableService;
	@Autowired
	private JsService jsService;
	@Autowired
	private JsDetilService jsDetilService;
	@Autowired
	private NewReService newReService;
	
	@ModelAttribute
	public RecivedDetil get(@RequestParam(required=false) String id) {
		RecivedDetil entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = recivedDetilService.get(id);
		}
		if (entity == null){
			entity = new RecivedDetil();
		}
		return entity;
	}
	
	/**
	 * 收款明细列表页面
	 */
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/recivedDetilList";
	}
	
		/**
	 * 收款明细列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "data")
	public Map<String, Object> data(RecivedDetil recivedDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<RecivedDetil> page = recivedDetilService.findPage(new Page<RecivedDetil>(request, response), recivedDetil); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑收款明细表单页面
	 */
	@RequestMapping(value = "form")
	public String form(RecivedDetil recivedDetil, Model model,String i,String sy) {
		recivedDetil.setRecive(i);
		Js js=jsService.get(i);
		model.addAttribute("r", js);
		model.addAttribute("recivedDetil", recivedDetil);
		model.addAttribute("sy", sy);
		return "modules/fee/recivedDetilForm";
	}

	/**
	 * 保存收款明细
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxJson save(RecivedDetil recivedDetil, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, recivedDetil)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		NumberFormat nf = NumberFormat.getInstance();
		 Js js=jsService.get(recivedDetil.getRecive());
		Double d=recivedDetil.getMoney();
		String  dd=js.getKpje();
		JsDetil jd=new JsDetil();
		jd.setJs(js.getId());
		List<JsDetil> list=jsDetilService.findList(jd);
		for(JsDetil jsd:list){
			NewRe n=newReService.get(jsd.getPid());
			String dz=n.getDzje();
			String kp=n.getKpje();
			double pj=d/Double.parseDouble(dd)*Double.parseDouble(kp);
			double dzje=Double.parseDouble(dz)+pj;
			n.setDzje(dzje+"");
			newReService.save(n);
		}

		Double e=Double.parseDouble(js.getHxje().replace(",",""));
		Double f=Double.parseDouble(js.getWhxje().replace(",",""));
		js.setHxje(nf.format(e+d).replaceAll(",",""));
		js.setWhxje(nf.format(f-d).replaceAll(",",""));
		if(js.getWhxje().equals("0.0")||js.getWhxje().equals("0")){
			js.setStatus("已核销");
		}else if(js.getHxje().equals("0")||js.getHxje().equals("0.0")){
			js.setStatus("未核销");
		}else{

			js.setStatus("部分核销");
		}
		jsService.save(js);
		recivedDetilService.save(recivedDetil);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存收款明细成功");
		return j;
	}
	
	/**
	 * 删除收款明细
	 */
	@ResponseBody
	@RequestMapping(value = "delete")
	public AjaxJson delete(RecivedDetil recivedDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		recivedDetilService.delete(recivedDetil);
		j.setMsg("删除收款明细成功");
		return j;
	}
	
	/**
	 * 批量删除收款明细
	 */
	@ResponseBody
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			recivedDetilService.delete(recivedDetilService.get(id));
		}
		j.setMsg("删除收款明细成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:recivedDetil:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(RecivedDetil recivedDetil, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "收款明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<RecivedDetil> page = recivedDetilService.findPage(new Page<RecivedDetil>(request, response, -1), recivedDetil);
    		new ExportExcel("收款明细", RecivedDetil.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出收款明细记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:recivedDetil:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RecivedDetil> list = ei.getDataList(RecivedDetil.class);
			for (RecivedDetil recivedDetil : list){
				try{
					recivedDetilService.save(recivedDetil);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条收款明细记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条收款明细记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入收款明细失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/recivedDetil/?repage";
    }
	
	/**
	 * 下载导入收款明细数据模板
	 */
	@RequiresPermissions("fee:recivedDetil:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "收款明细数据导入模板.xlsx";
    		List<RecivedDetil> list = Lists.newArrayList(); 
    		new ExportExcel("收款明细数据", RecivedDetil.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/recivedDetil/?repage";
    }

}